<?php

namespace app\manage\controller;

use app\common\model\Group;
use think\Request;
use app\common\model\User as UserM;
use app\common\validate\User as UserV;

class User extends Base
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        // 当前用户所管理的所有用户，不包含自己
        $field = ['id', 'username', 'name', 'group_id', 'name', 'email', 'phone','status'];
        $map = [];
        $map[] = ['id', '>', $this->baseInfo['uid']];

        // 根据查询到的用户组判断当前管理员是否有操作用户的权限
        $list = UserM::where($map)->field($field)->select();

        $data = [
            'items' => $list ?: [],
            'total' => $list->count()
        ];
        return $this->result_json(null, 1, $data);
    }

    public function create() {
        $map = [];
        $map[] = ['pid', '>=', $this->baseInfo['group']];
        $map[] = ['status', '=', 1];
        $list = Group::where($map)->field(['id', 'name', 'pid'])->select();
        // 查询后，再判断path中是否包含gid
        // 递归处理数据为children，递归的时候可以实现自动去掉无关子级

        $data = [
            'group' => $list ?: []
        ];
        return $this->result_json(null, 1, $data);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        // 数据获取和检查
        $validate = new UserV();
        $data = $request->only(['username', 'password', 'repwd', 'group_id', 'name', 'phone', 'email', 'status']);
        if (!$validate->scene('New')->check($data)) {
            return $this->result_json($validate->getError(), 201);
        }

        $instance = new UserM();
        if ($instance->save($data)) {
            return $this->result_json('create success', 0, ['id' => $instance->id]);
        } else {
            return $this->result_json('db error', 101);
        }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {

    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        // 字段验证和合法性验证
        $validate = new UserV();
        $data = $request->only(['username', 'password', 'repwd', 'group_id', 'name', 'phone', 'email', 'status']);
        if (!$validate->scene('Update')->check($data)) {
            return $this->result_json($validate->getError(), 201);
        }

        // 数据库同步
        $instance = UserM::get($id);    // 是否只查询单个字段
        if ($instance) {
            if ($instance->save($data)) {
                return $this->result_json('update success', 0);
            }
            return $this->result_json('db error', 101);
        } else {
            return $this->result_json('该用户不存在', 202);
        }
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id, $flag = true)
    {
        $map = [];
        // 是否现判断数据是否存在
        $instance = UserM::alias('u')->where($map)->field(['u.status', 'g.path'])
            ->leftJoin('group g', 'u.group_id = g.id')
            ->find($id);

        if (!$instance) return $this->result_json('param error', 201);
        if (!$this->validateUser($instance->path))
            return $this->result_json('param error', 201);

        $instance->status = $flag === 'true' ? -1 : 1;
        if ($instance->save() === false) {
            return $this->result_json('param error', 201);
        }
        return $this->result_json('delete success', 0);
    }

    private function validateUser($path) {
        if (!$path) {
            return true;
        } else {
            $paths = explode(',', $path);
            if (in_array($this->baseInfo['group'], $paths)) {
                return true;
            }
            return false;
        }
    }
}
